<?php

namespace App\Admin\Extensions;

//use Dcat\Admin\Show\AbstractTool;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use ReflectionClass;

class FilterAwareNavigation
{
    /**
     * 获取相邻记录
     *
     */
    public static function getAdjacentRecord($builder, $model, $queryParams, $type = 'next')
    {
        $builder = clone $builder;
        // 获取排序字段和方向
        $orderColumn    = $queryParams['_sort'] ?? 'id';
        $orderDirection = $queryParams['_order'] ?? 'desc';
        if ($type === 'prev') {
            // 上一页记录
            return $builder
                ->where(function($query) use ($model, $orderColumn, $orderDirection) {
                    // 主要排序字段值大于当前记录值
                    $query->where($orderColumn, $orderDirection === 'desc' ? '>' : '<', $model->$orderColumn)
                        // 或者值相等但ID更小(或更大)
                        ->orWhere(function($q) use ($model, $orderColumn, $orderDirection) {
                            $q->where($orderColumn, $model->$orderColumn)
                                ->where('id', $orderDirection === 'desc' ? '>' : '<', $model->id);
                        });
                })
                ->orderBy($orderColumn, $orderDirection === 'desc' ? 'asc' : 'desc')
                ->orderBy('id', $orderDirection === 'desc' ? 'asc' : 'desc')
                ->first();
        } else {
            // 下一页记录
            return $builder
                ->where(function($query) use ($model, $orderColumn, $orderDirection) {
                    // 主要排序字段值小于当前记录值
                    $query->where($orderColumn, $orderDirection === 'desc' ? '<' : '>', $model->$orderColumn)
                        // 或者值相等但ID更大(或更小)
                        ->orWhere(function($q) use ($model, $orderColumn, $orderDirection) {
                            $q->where($orderColumn, $model->$orderColumn)
                                ->where('id', $orderDirection === 'desc' ? '<' : '>', $model->id);
                        });
                })
                ->orderBy($orderColumn, $orderDirection)
                ->orderBy('id', $orderDirection)
                ->first();
        }
    }

    /**
     * 获取上一页按钮
     *
     */
    public static function getTurnPageButton($url, $queryParams, $type = 'prev')
    {
        $url = admin_url($url . '?' . http_build_query($queryParams));
        $button = '<a class="btn btn-sm btn-primary" href="' . $url .'">';
        if ($type == 'prev'){
            $button .= '<i class="fa fa-arrow-left"></i> 上一页</a>';
        }else{
            $button .= '下一页 <i class="fa fa-arrow-right"></i></a>';
        }
        return $button;
    }

}
